#!/usr/bin/python
# -*- coding: cp1250 -*-

import string
import re
import sys
import pepe.p_txt.bigtxt as bt
import pepe.p_txt.findcdelimiter as fcd

def main(inpfile, corder):
    '''
    Purpose:    Reorder columns in text file.\n
    Syntax:     csv_cmix3 <inputfile> <columns order>
    Example:    csv_cmix3 in.csv "3,6"
    '''
    co = corder.split(',')
    co.reverse()
    outf = open(inpfile+'.csv_cmix3', 'w') 
    cd = ""
    for line in bt.lines(inpfile):
        line = re.sub('\n', '', line)

        # find out column delimiter
        if cd == "": cd = fcd.fcd(line)

        cols = line.split(cd)
        # prepare index list
        idxl = range(1, len(cols)+1)
        for i in co:
            idxl.remove(int(i))
            idxl.insert(0,int(i))
        # select columns using index list
        for i in idxl:
            outf.write("%s%s" % (cols[i-1], cd))
        outf.write("\n")
    outf.close()

if __name__ == "__main__":
    ''' '''
    if  len(sys.argv) <> 3:
        print main.__doc__
    else:
        main(sys.argv[1], sys.argv[2])